﻿using System.Collections.Generic;
using Inovout.Repositories;
using Inovout.Models;
using System.Linq;

namespace Inovout.Services
{
    public class RepositoryService<TEntity> : BaseService, IRepositoryService<TEntity>, IRepositoryService 
        where TEntity : class
    {
        public virtual void Save(TEntity entity)
        {
            DataObject dataObject = entity as DataObject;
            if (ValueComparer.DefaultValueEquals(dataObject.Id))
            {
                Create(entity);
            }
            else
            {
                Update(entity);
            }
        }

        public virtual void Create(TEntity entity)
        {
            Repository.Save(entity);
        }
        public virtual void Update(TEntity entity)
        {
            Repository.Save(entity);
        }
        protected IRepository<TEntity> Repository
        {
            get { return repository as IRepository<TEntity>; }
        }
        public virtual IEnumerable<TEntity> FindAll()
        {
            return Repository.FindAll();
        }
        public virtual int Count()
        {
            return Repository.Count();
        }
        public virtual void Delete(object id)
        {
            Repository.Delete(id);
        }
        public virtual IDataObjectPagedSet<TEntity> FindAll(int pageIndex, int pageSize = 20)
        {
            return Repository.FindAll(pageSize, pageIndex, null);
        }
        public virtual TEntity FindById(object id)
        {
            return Repository.FindById(id);
        }
        public virtual IQueryable<TEntity> Query()
        {
            return Repository.Query();
        }
        void IRepositoryService.Save(object model)
        {
            this.Save((TEntity)model);
        }

        object IRepositoryService.FindById(object id)
        {
            return ((IRepository)Repository).FindById(id);
        }


        public bool IsUnique(object id, string propertyName, object propertyVallue)
        {
            return Repository.IsUnique(id, propertyName, propertyVallue);
        }

        protected void Evict(TEntity entity)
        {
            ((BaseRepository<TEntity>)repository).Evict(entity);
        }
    }
}
